<!DOCTYPE html>
<html>
<head>
	<title>Test _StoreMixinLeak</title>
	<meta name="viewport"
		  content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no"/>
	<meta name="apple-mobile-web-app-capable" content="yes"/>
	<script type="text/javascript" src="../../../deviceTheme.js"></script>
	<script type="text/javascript" src="../../../../../dojo/dojo.js" data-dojo-config="async: true, parseOnLoad: false"></script>
	<script type="text/javascript">
		require([
			"dojo/store/Memory",
			"dojo/store/Observable",
			"dojo/_base/declare",
			"dojo/Deferred",
			"dojo/store/util/QueryResults",
			"dojo/store/util/SimpleQueryEngine",
			"dojox/mobile/_StoreMixin",
			"doh/runner",
			"dojo/ready"
		], function(Memory, Observable, declare, Deferred, QueryResults, SimpleQueryEngine, _StoreMixin, runner, ready){

			var static_data = [
					{id: 1, label: "Apple", moveTo: "dummy"},
					{id: 2, label: "Banana", moveTo: "dummy"},
					{id: 9, label: "Peach", moveTo: "dummy"}
				],
				delay = 2000;

			var DeferredMemory = declare([Memory], {
				query: function(query, options){
					var r = this.data,
						d = new Deferred();
					setTimeout(function(){
						d.resolve(r);
					}, delay);
					return QueryResults(d);
				}
			});
			var StoreConsumer = declare([_StoreMixin], {
				onComplete: function(items){},
				onError: function(errorData){},
				onUpdate: function(item, insertedInto){},
				onDelete: function(item, removedFrom){}
			});

			var removed = 0;
			function patchRemove(h){
				var old = h.remove;
				h.remove = function(){
					if (!h.removed){
						h.removed = true;
						++removed;
					}
					return old.apply(this, arguments);
				}
			}

			ready(function(){
				runner.register("dojox.mobile.tests.doh.storemixin.StoreMixinLeakTest", [
					{
						name: "test for #17407: obervable handlers not removed",
						timeout:10000,
						runTest: function(t){
							var def = new runner.Deferred(),
								sc = new StoreConsumer(),
								store = Observable(new DeferredMemory({data: static_data}));
							// [1]
							sc.setStore(store).then(function(){patchRemove(sc._observe_h);});
							var f = def.getTestCallback(function(){
								t.assertEqual(2, removed, "Unexpected removed handlers count.");
							});
							setTimeout(function(){
								// execute it once the first query [1] has completed
								sc.refresh().then(function(){patchRemove(sc._observe_h);});
								sc.refresh().then(function(){patchRemove(sc._observe_h);});
								setTimeout(f, 2*delay);
							},delay+500);
							return def;
						}
					}
				]);
				runner.run();
			});
		});
	</script>
</head>
</html>
